import { MSG_TYPES } from '../../utils/MESSAGE_TYPES'

export default function (xhr, PROXY_ROUTES = []) {
  const { bgReqId: id, open } = xhr
  return function (method, url, async, user, password) {
    xhr.url = url
    // 判断是否需要代理
    if (PROXY_ROUTES.filter(({ enable }) => enable).some(({ matching }) => {
      const REG = new RegExp(matching, 'g')
      return REG.test(url)
    })) {
      window.postMessage({
        event: MSG_TYPES.open,
        id,
        data: {
          method,
          url,
          async,
          user,
          password
        }
      })
    } else {
      open.call(xhr, ...arguments)
    }
  }
}
